﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Bifrost;
using DevComponents.AdvTree;
using TextEditor.TextDocument.Document;
using TextEditor.TextDocument.frmWindow;

namespace TextEditor.TextDocument.Control
{
    public partial class frmDiagnoseSimple : DevComponents.DotNetBar.Office2007Form
    {
        ZYTextDocument document;
        public frmDiagnoseSimple(ZYTextDocument _document)
        {
            InitializeComponent();
            this.tcpWestern.Controls.Add(this.txtDiagnose.listBoxAutoComplete);
            this.txtDiagnose.SetPoint();
            this.txtDiagnose.OnReturnId = ReturnId;
            this.tcpChinese.Controls.Add(this.txtBm.listBoxAutoComplete);
            this.txtBm.SetPoint();
            this.txtBm.SetSql(" select bm_name name,bm_code id,bm_name||'  '||bm_code as ni from t_bm where lower(py) like '{0}%' UNION all select bm_name name,bm_code id,bm_name||'  '||bm_code as ni from t_bm where lower(wb) like '{0}%' UNION all select bm_name name,bm_code id,bm_name||'  '||bm_code as ni from t_bm where bm_name like '%{0}%'");
            this.txtBm.OnReturnId = ReturnId2;
            this.tcpChinese.Controls.Add(this.txtZh.listBoxAutoComplete);
            this.txtZh.SetSql(" select zh_name name,zh_code id,zh_name||'  '||zh_code as ni from t_zh where lower(py) like '{0}%' UNION all select zh_name name,zh_code id,zh_name||'  '||zh_code as ni from t_zh where lower(wb) like '{0}%' UNION all select zh_name name,zh_code id,zh_name||'  '||zh_code as ni from t_zh where zh_name like '%{0}%'");
            this.txtZh.SetPoint();
            this.txtZh.OnReturnId = ReturnId3;
            document = _document;
            RefreshDiagnose(atDiagnoseList, "");
            RefreshDiagnose(atChineseDiagnose, "Y");
            this.cbDiagnoseBox.SelectedIndex = 0;
            cbiSelectAll_Click(null, null);
        }

        string action = string.Empty;
        string caction = string.Empty;

        public void RefreshDiagnose(AdvTree diagnoseTree, string isChinese)
        {
            diagnoseTree.Nodes.Clear();
            string sqlMainDiagnose = string.Format("select id,diagnose_code,create_time,diagnose_name, diagnose_icd10,diagnose_sort,SYMPTOMS_NAME,SYMPTOMS_CODE from t_simple_diagnose where patient_id = '{0}' {1} order by diagnose_sort", document.Us.InpatientInfo.Id, isChinese == "" ? "and (is_chinese is null or is_chinese = 'N') " : "and is_chinese = 'Y'");
            DataTable mainDt = App.GetDataSet(sqlMainDiagnose).Tables[0];
            if (mainDt != null && mainDt.Rows.Count > 0)
            {
                foreach (DataRow mainRow in mainDt.Rows)
                {
                    Node parentNode = new Node();
                    parentNode.Name = mainRow["id"].ToString();
                    parentNode.Text = mainRow["diagnose_name"].ToString();
                    parentNode.Tag = mainRow;
                    parentNode.CheckBoxVisible = true;

                    if (isChinese == "Y")
                    {
                        parentNode.Cells.Add(new Cell(mainRow["SYMPTOMS_NAME"].ToString()));
                    }
                    else
                    {

                        parentNode.Cells.Add(new Cell(mainRow["diagnose_code"].ToString()));
                    }
                    string sqlTrendDiagnose = string.Format("select id, trend_diagnose_name, diagnose_icd10, diagnose_code, sort_sequence, parent_id from t_simple_trend_diagnose where diagnoseitem_id = '{0}' order by sort_sequence", parentNode.Name);
                    DataTable trendDt = App.GetDataSet(sqlTrendDiagnose).Tables[0];
                    if (trendDt != null && trendDt.Rows.Count > 0)
                        AddTrendDiagnose(parentNode, parentNode.Name, trendDt, parentNode.Name, isChinese);
                    diagnoseTree.Nodes.Add(parentNode);
                }
            }
            diagnoseTree.ExpandAll();
        }

        public void ReturnId(string icd)
        {
            if (icd == "add")
            {
                btnAdd_Click(null, null);
            }
            else
            {
                this.lblIcd10Encode.Text = icd;
            }
        }

        public void ReturnId2(string icd)
        {
            if (icd == "add")
            {
                if (this.txtZh.Enabled == false)
                {
                    btnChineseAdd_Click(null, null);
                }
                else
                {
                    this.txtZh.Focus();
                }
            }
            else
            {
                this.lbChineseBmIcd.Text = icd;
            }
        }

        public void ReturnId3(string icd)
        {
            if (icd == "add")
            {
                btnChineseAdd_Click(null, null);
            }
            else
            {
                this.lbChineseZhIcd.Text = icd;
            }
        }

        static void AddTrendDiagnose(Node parentNode, string parentId, DataTable trendDt, string parentName, string icChinese)
        {
            DataRow[] dr = trendDt.Select(string.Format("parent_id = '{0}'", parentId));
            if (dr != null && dr.Length > 0)
            {
                foreach (DataRow trendRow in dr)
                {
                    Node childNode = new Node();
                    childNode.CheckBoxVisible = true;
                    childNode.Name = trendRow["id"].ToString();
                    childNode.Text = trendRow["trend_diagnose_name"].ToString();
                    if (icChinese != "Y")
                        childNode.Cells.Add(new Cell(trendRow["diagnose_icd10"].ToString()));
                    childNode.Tag = trendRow;
                    if (childNode.Name != parentId && childNode.Name != parentName)
                        AddTrendDiagnose(childNode, childNode.Name, trendDt, parentName, icChinese);
                    parentNode.Nodes.Add(childNode);
                }
            }
        }

        private void biUp_Click(object sender, EventArgs e)
        {
            //Node selectNode = this.atDiagnoseList.SelectedNode;
            //if (selectNode != null && selectNode.Index > 0)
            //{
            //    Node PrentNode = GetParentNode(selectNode);
            //    Node preNode = selectNode.PrevNode;
            //    Node newNode = selectNode.Copy();
            //    CopyToNode(selectNode, newNode);
            //    if (selectNode.Parent == null)
            //    {
            //        this.atDiagnoseList.Nodes.Insert(preNode.Index, newNode);
            //        this.atDiagnoseList.Nodes.Remove(selectNode);
            //        this.atDiagnoseList.SelectedNode = newNode;
            //        InterChangerParentId(newNode, preNode);
            //    }
            //    else
            //    {
            //        preNode.Parent.Nodes.Insert(preNode.Index, newNode);
            //        preNode.Parent.Nodes.Remove(selectNode);
            //        this.atDiagnoseList.SelectedNode = newNode;
            //        InterchangeNodeId(newNode, preNode);
            //    }
            //}

            ChangedNodeMoveUp(atDiagnoseList);
        }

        static void ChangedNodeMoveUp(AdvTree tree)
        {
            Node selectNode = tree.SelectedNode;
            if (selectNode != null && selectNode.Index > 0)
            {
                Node PrentNode = GetParentNode(selectNode);
                Node preNode = selectNode.PrevNode;
                Node newNode = selectNode.Copy();
                CopyToNode(selectNode, newNode);
                if (selectNode.Parent == null)
                {
                    tree.Nodes.Insert(preNode.Index, newNode);
                    tree.Nodes.Remove(selectNode);
                    tree.SelectedNode = newNode;
                    InterChangerParentId(newNode, preNode);
                }
                else
                {
                    preNode.Parent.Nodes.Insert(preNode.Index, newNode);
                    preNode.Parent.Nodes.Remove(selectNode);
                    tree.SelectedNode = newNode;
                    InterchangeNodeId(newNode, preNode);
                }
            }
        }

        static void ChangedNodeMoveDown(AdvTree tree)
        {
            Node selectNode = tree.SelectedNode;
            if (selectNode != null && selectNode.NextNode != null)
            {
                Node PrentNode = GetParentNode(selectNode);
                Node nextNode = selectNode.NextNode;
                Node newNode = selectNode.Copy();
                CopyToNode(selectNode, newNode);
                if (selectNode.Parent == null)
                {
                    tree.Nodes.Insert(nextNode.Index + 1, newNode);
                    tree.Nodes.Remove(selectNode);
                    tree.SelectedNode = newNode;
                    InterChangerParentId(newNode, nextNode);
                }
                else
                {
                    nextNode.Parent.Nodes.Insert(nextNode.Index + 1, newNode);
                    nextNode.Parent.Nodes.Remove(selectNode);
                    tree.SelectedNode = newNode;
                    InterchangeNodeId(newNode, nextNode);
                }
            }
        }

        /// <summary>
        /// 交换排序ID
        /// </summary>
        /// <param name="_node1"></param>
        /// <param name="_node2"></param>
        /// <returns></returns>
        static int InterchangeNodeId(Node _node1, Node _node2)
        {
            string sql1 = string.Format("UPDATE t_simple_trend_diagnose T set T.sort_sequence = '{0}' WHERE T.ID = '{1}'", _node1.Index, _node1.Name);
            string sql2 = string.Format("UPDATE t_simple_trend_diagnose Y set Y.sort_sequence = '{0}' WHERE Y.ID = '{1}'", _node2.Index, _node2.Name);
            return App.ExecuteBatch(new string[] { sql1, sql2 });
        }

        static int InterChangerParentId(Node _node1, Node _node2)
        {
            string sql1 = string.Format("UPDATE t_simple_diagnose T set T.diagnose_sort = '{0}' WHERE T.ID = '{1}'", _node1.Index, _node1.Name);
            string sql2 = string.Format("UPDATE t_simple_diagnose Y set Y.diagnose_sort = '{0}' WHERE Y.ID = '{1}'", _node2.Index, _node2.Name);
            return App.ExecuteBatch(new string[] { sql1, sql2 });
        }

        /// <summary>
        /// 获取顶级节点
        /// </summary>
        /// <param name="_node"></param>
        /// <returns></returns>
        static Node GetParentNode(Node _node)
        {
            Node node = _node;
            while (node.Parent != null)
            {
                node = node.Parent;
            }
            return node;
        }

        /// <summary>
        /// 复制到新节点
        /// </summary>
        /// <param name="oldNode"></param>
        /// <param name="newNode"></param>
        /// <returns></returns>
        static void CopyToNode(Node oldNode, Node newNode)
        {
            foreach (Node childNode in oldNode.Nodes)
            {
                Node newChildNode = childNode.Copy();
                newNode.Nodes.Add(newChildNode);
                CopyToNode(childNode, newChildNode);
            }
        }

        private void biDown_Click(object sender, EventArgs e)
        {
            ChangedNodeMoveDown(atDiagnoseList);
        }



        private void btnAdd_Click(object sender, EventArgs e)
        {
            string diagnoseName = this.txtDiagnose.Text.Trim().Replace("'", "''");
            string timeStr = App.GetSystemTime().ToString("yyyy-MM-dd HH:mm:ss");
            if (string.IsNullOrEmpty(diagnoseName))
            {
                App.Msg("[诊断名称]未填写完整！");
                return;
            }

            if (this.action == "trend")
            {
                Node selectNode = this.atDiagnoseList.SelectedNode;
                if (selectNode != null)
                {
                    Node parentNode = GetParentNode(selectNode);

                    int num = 0;
                    if (selectNode.Nodes.Count > 0)
                    {
                        int.TryParse((selectNode.Nodes[selectNode.Nodes.Count - 1].Tag as DataRow)["sort_sequence"].ToString(), out num);
                    }
                    t_simple_trend_diagnose tstd = new t_simple_trend_diagnose(parentNode.Name, diagnoseName, this.lblIcd10Encode.Text, this.lblIcd10Encode.Text, num + 1, selectNode.Name);
                    if (tstd.Insert())
                    {
                        App.Msg("附属诊断添加成功！");
                    }
                }
            }
            else if (this.action == "update")
            {
                Node selectNode = this.atDiagnoseList.SelectedNode;
                if (selectNode != null)
                {
                    if (selectNode.Parent == null)
                    {
                        t_simple_diagnose tsd = new t_simple_diagnose(this.lblIcd10Encode.Text, "", diagnoseName, this.lblIcd10Encode.Text, 0, 0);
                        if (tsd.Update(selectNode.Name))
                        {
                            App.Msg("诊断修改成功！");
                        }
                    }
                    else
                    {
                        t_simple_trend_diagnose tstd = new t_simple_trend_diagnose("", diagnoseName, this.lblIcd10Encode.Text, this.lblIcd10Encode.Text, 0, "");
                        if (tstd.Update(selectNode.Name))
                        {
                            App.Msg("附属诊断修改成功！");
                        }
                    }
                }
            }
            else
            {
                int num = 0;
                if (this.atDiagnoseList.Nodes.Count > 0)
                {
                    int.TryParse((this.atDiagnoseList.Nodes[this.atDiagnoseList.Nodes.Count - 1].Tag as DataRow)["diagnose_sort"].ToString(), out num);
                }
                t_simple_diagnose tsd = new t_simple_diagnose(this.lblIcd10Encode.Text, timeStr, diagnoseName, this.lblIcd10Encode.Text, num + 1, document.Us.InpatientInfo.Id);
                if (tsd.Insert())
                {
                    App.Msg("诊断添加成功！");
                }
            }
            this.action = string.Empty;
            this.atDiagnoseList.Enabled = true;
            this.clearDiagnose();
            RefreshDiagnose(atDiagnoseList, "");
        }

        private void 添加附属诊断ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Node selectNode = this.atDiagnoseList.SelectedNode;
            if (selectNode != null)
            {
                this.action = "trend";
                this.atDiagnoseList.Enabled = false;
                clearDiagnose();
            }
            else
            {
                App.Msg("请选中要添加附属诊断的节点！");
            }
        }

        void clearDiagnose()
        {
            this.lblIcd10Encode.Text = "";
            this.txtDiagnose.Text = "";
        }

        void clearChineseDiagnose()
        {
            this.lbChineseBmIcd.Text = "";
            this.lbChineseZhIcd.Text = "";
            this.txtBm.Text = "";
            this.txtZh.Text = "";
            this.txtZh.Enabled = true;
        }

        private void atDiagnoseList_NodeDoubleClick(object sender, TreeNodeMouseEventArgs e)
        {
            Node selectNode = (sender as AdvTree).SelectedNode;
            if (selectNode != null)
            {
                selectNode.Checked = !selectNode.Checked;
            }
        }

        static void ChildCheck(Node node, bool b)
        {
            if (node.Nodes.Count > 0)
            {
                foreach (Node childNode in node.Nodes)
                {
                    childNode.Checked = b;
                    ChildCheck(childNode, b);
                }
            }
        }

        private void atDiagnoseList_AfterCheck(object sender, AdvTreeCellEventArgs e)
        {
            if (changed)
                return;
            Node selectNode = this.atDiagnoseList.SelectedNode;
            if (selectNode != null)
            {
                ChildCheck(selectNode, selectNode.Checked);
            }
        }

        private void atDiagnoseList_NodeMouseDown(object sender, TreeNodeMouseEventArgs e)
        {
            Node findNode = this.atDiagnoseList.GetNodeAt(e.Y);
            if (findNode != null)
            {
                //this.atDiagnoseList.SelectedNode = findNode;
            }
        }

        private void 删除诊断ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Node selectNode = this.atDiagnoseList.SelectedNode;

            if (selectNode != null)
            {
                if (MessageBox.Show("确定要删除该诊断吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.No)
                    return;
                if (selectNode.Parent == null)
                {
                    t_simple_diagnose.Delete(selectNode.Name);
                    t_simple_trend_diagnose.Delete(selectNode.Name, 1);
                }
                else
                {
                    t_simple_trend_diagnose.Delete(selectNode.Name, 0);
                }
            }
            this.action = string.Empty;
            this.atDiagnoseList.Enabled = true;
            this.clearDiagnose();
            RefreshDiagnose(atDiagnoseList, "");
        }

        private void 修改诊断ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Node selectNode = this.atDiagnoseList.SelectedNode;
            if (selectNode != null)
            {
                this.action = "update";
                this.atDiagnoseList.Enabled = false;
                this.txtDiagnose.Text = selectNode.Text;
                this.lblIcd10Encode.Text = ((DataRow)selectNode.Tag)["diagnose_code"].ToString();
            }
            else
            {
                App.Msg("请选中要修改的诊断节点！");
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            this.action = string.Empty;
            this.atDiagnoseList.Enabled = true;
            this.clearDiagnose();
        }
        bool changed = false;
        private void cbiSelectAll_Click(object sender, EventArgs e)
        {
            changed = true;
            if (this.atDiagnoseList.Nodes.Count > 0)
            {
                foreach (Node node in this.atDiagnoseList.Nodes)
                {
                    node.Checked = cbiSelectAll.Checked;
                    ChildCheck(node, node.Checked);
                }
            }
            changed = false;
        }

        bool isCheckedMore(Node tvNode)
        {
            if (tvNode.Nodes.Count > 0)
            {
                int count1 = 0;
                foreach (Node node in tvNode.Nodes)
                {
                    if (node.Checked)
                    {
                        count1++;
                    }
                    if (count1 > 1)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        bool isCheckedMore(AdvTree tvNode)
        {
            if (tvNode.Nodes.Count > 0)
            {
                int count1 = 0;
                foreach (Node node in tvNode.Nodes)
                {
                    if (node.Checked)
                    {
                        count1++;
                    }
                    if (count1 > 1)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            if (this.cbDiagnoseBox.SelectedIndex == 0)
            {
                App.Msg("请选择要插入的诊断类别！");
                return;
            }
            List<Diagnose_item> diagnoseStr = new List<Diagnose_item>();
            string selectType = this.cbDiagnoseBox.Text;
            StringBuilder DiagnoseIdbuilder = new StringBuilder("diagnoseid_");
            List<string> sqlList = new List<string>();
            bool b = this.document.IshaveDiagnoseDiv(selectType);
            string createTime = App.GetSystemTime().ToString("yyyy-MM-dd HH:mm:ss");
            if (b)
            {
                string diagnoseType = TextDocument.frmWindow.frmDiagnoseModify.diagnoseTypeNO(selectType);
                if (!document.SqlDiagnoseList.ContainsKey(diagnoseType))
                {
                    document.SqlDiagnoseList.Add(diagnoseType, sqlList);
                }
                else
                {
                    document.SqlDiagnoseList[diagnoseType] = sqlList;
                }

                sqlList.Add("delete t_trend_diagnose where diagnoseitem_id in(select id from t_diagnose_item where doc_id = '{0}' and diagnose_type ='" + diagnoseType + "')");
                sqlList.Add("delete t_diagnose_item where doc_id = '{0}' and diagnose_type ='" + diagnoseType + "'");
            }

            bool haveChinese = false;
            int count2 = 1;
            bool haveMore = isCheckedMore(this.atChineseDiagnose);
            bool haveMore2 = isCheckedMore(this.atDiagnoseList);
            foreach (Node diagnoseNode in this.atChineseDiagnose.Nodes)
            {
                if (diagnoseNode.Checked)
                {
                    haveChinese = true;
                    if (diagnoseStr.Count > 0)
                    {
                        DiagnoseIdbuilder.Append("|");
                    }
                    Diagnose_item item = new Diagnose_item();

                    if (count2 == 1)
                    {
                        item.DiagnoseName = "中医诊断:" + (haveMore ? count2.ToString() + "." : "") + diagnoseNode.Text;
                        item.ZyStart = true;
                    }
                    else
                    {
                        item.DiagnoseName = count2.ToString() + "." + diagnoseNode.Text;
                    }
                    item.Lever = diagnoseNode.Level;
                    item.Index = count2;
                    diagnoseStr.Add(item);
                    Diagnose_item item2 = new Diagnose_item();
                    item2.DiagnoseName = diagnoseNode.Cells[1].Text.Trim();
                    item2.Lever = diagnoseNode.Level + 1;
                    item2.Index = 0;
                    if (!string.IsNullOrEmpty(item2.DiagnoseName))
                        diagnoseStr.Add(item2);
                    GetSelectListString(diagnoseNode, diagnoseStr, true);
                    DiagnoseIdbuilder.Append(diagnoseNode.Name);
                    if (b)
                    {
                        GetSql(diagnoseNode.Name, selectType, sqlList, createTime, diagnoseNode);
                    }
                    count2++;
                }
            }

            int count = 1;
            foreach (Node diagnoseNode in this.atDiagnoseList.Nodes)
            {
                if (diagnoseNode.Checked)
                {
                    if (diagnoseStr.Count > 0)
                    {
                        DiagnoseIdbuilder.Append("|");
                    }
                    Diagnose_item item = new Diagnose_item();
                    if (haveChinese && count == 1)
                    {
                        item.DiagnoseName = "西医诊断:" + (haveMore2 ? count.ToString() + "." : "") + diagnoseNode.Text;
                        item.ZyStart = true;
                    }
                    else
                    {
                        item.DiagnoseName = (haveMore2 ? count.ToString() + "." : "") + diagnoseNode.Text;
                    }
                    item.Lever = diagnoseNode.Level;
                    item.Index = count;
                    diagnoseStr.Add(item);
                    GetSelectListString(diagnoseNode, diagnoseStr, false);
                    DiagnoseIdbuilder.Append(diagnoseNode.Name);
                    if (b)
                    {
                        GetSql(diagnoseNode.Name, selectType, sqlList, createTime, diagnoseNode);
                    }
                    count++;
                }
            }


            this.document.RefreshDiagnose(this.cbDiagnoseBox.Text, diagnoseStr, DiagnoseIdbuilder.ToString());
            this.Close();
        }

        private void GetSelectListString(Node _diagnoseNode, List<Diagnose_item> diagnoseStrs, bool isChinese)
        {
            int index = 0;
            bool haveMore = isCheckedMore(_diagnoseNode);
            foreach (Node _childNode in _diagnoseNode.Nodes)
            {
                if (_childNode.Checked)
                {
                    Diagnose_item item = new Diagnose_item();
                    //if (_childNode.Level == 1)
                    //{
                    item.DiagnoseName = (haveMore ? (index + 1).ToString() + "）" : "") + _childNode.Text;
                    //}
                    //else
                    //{
                    //    item.DiagnoseName = _childNode.Text;
                    //}
                    item.Lever = _childNode.Level;
                    item.Index = _childNode.Index + 1;
                    diagnoseStrs.Add(item);
                    GetSelectListString(_childNode, diagnoseStrs, isChinese);
                    index++;
                }
            }
        }

        /// <summary>
        /// 复制诊断
        /// </summary>
        /// <param name="diagnoseid"></param>
        /// <param name="type"></param>
        /// <param name="sqlList"></param>
        /// <param name="create_time"></param>
        private void GetSql(string diagnoseid, string type, List<string> sqlList, string create_time, Node treeNode)
        {
            string id = App.GetDataSet("select T_DIAGNOSE_ITEM_ID.nextval from dual").Tables[0].Rows[0][0].ToString();
            string sql = "INSERT INTO t_diagnose_item(    "   //新增诊断条目
                                    + " id,                     "
                                    + " diagnose_code,          "
                                    + " create_time,            "
                                    + " create_id,              "
                                    + " diagnose_name,          "
                                    + " diagnose_icd10,         "
                                    + " is_chinese,              "
                                    + " turn_to,                "
                                    + " turn_to_other,          "
                                    + " patient_id,             "
                                    + " diagnose_sort,          "
                                    + " diagnose_type,          "
                                    + " text_id,                "
                                    + " doc_id,                 "
                                    + " SYMPTOMS_NAME,          "
                                    + " SYMPTOMS_CODE         )"
                                    + "SELECT "
                                    + "'" + id + "',"
                                    + "diagnose_code,"
                                    + "to_TIMESTAMP('" + create_time + "','yyyy-MM-dd hh24:mi:ss'),"
                                    + "'" + App.UserAccount.UserInfo.User_id + "',"
                                    + "diagnose_name,"
                                    + "diagnose_icd10,"
                                    + "is_chinese,"
                                    + "" + (type == "死亡诊断" ? "'死亡'" : type == "出院诊断" ? "'无'" : "''") + ","
                                    + "" + ((type == "死亡诊断" || type == "出院诊断") ? "to_TIMESTAMP('" + create_time + "','yyyy-MM-dd hh24:mi:ss')" : "''") + ","
                                    + "patient_id,"
                                    + "diagnose_sort,"
                                    + "'" + TextDocument.frmWindow.frmDiagnoseModify.diagnoseTypeNO(type) + "',"
                                    + "'" + document.Us.TextKind_id + "',"
                                    + "'{0}',"
                                    + "SYMPTOMS_NAME,"
                                    + "SYMPTOMS_CODE "
                                    + " FROM t_simple_diagnose "
                                    + " WHERE ID = '" + diagnoseid + "'";
            sqlList.Add(sql);
            SetCopyDiagnose(sqlList, treeNode, id, id);
        }

        private void SetCopyDiagnose(List<string> sqlList, Node _node, string id, string parentId)
        {
            foreach (Node childNode in _node.Nodes)
            {
                if (childNode.Checked)
                {
                    DataRow row = childNode.Tag as DataRow;
                    string newid = App.GetDataSet("select T_DIAGNOSE_ITEM_ID.nextval from dual").Tables[0].Rows[0][0].ToString(); //诊断条目ID
                    string sql = string.Format(" INSERT INTO T_TREND_DIAGNOSE (ID,DIAGNOSEITEM_ID,TREND_DIAGNOSE_NAME,DIAGNOSE_ICD10,DIAGNOSE_CODE,SORT_SEQUENCE,PARENT_ID) "
                               + " VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", newid, id, childNode.Text.Replace("'", "''"), row["DIAGNOSE_ICD10"].ToString(), row["DIAGNOSE_ICD10"].ToString(), childNode.Index, parentId);
                    if (childNode.Nodes.Count > 0)
                    {
                        SetCopyDiagnose(sqlList, childNode, id, newid);
                    }
                    sqlList.Add(sql);
                }
            }
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            frmDiagnoseModify fr = new frmDiagnoseModify(document);
            fr.ShowDialog();
        }

        private void atDiagnoseList_DoubleClick(object sender, EventArgs e)
        {
            atDiagnoseList_NodeDoubleClick(sender, null);
        }

        private void btnChineseClear_Click(object sender, EventArgs e)
        {
            this.caction = string.Empty;
            this.atChineseDiagnose.Enabled = true;
            this.clearChineseDiagnose();
        }

        private void btnChineseAdd_Click(object sender, EventArgs e)
        {
            string diagnoseBm = this.txtBm.Text.Trim();
            string diagnoseZh = this.txtZh.Text.Trim();
            if (string.IsNullOrEmpty(diagnoseBm))
            {
                App.Msg("[病名]未填写完整！");
                return;
            }

            string timeStr = App.GetSystemTime().ToString("yyyy-MM-dd HH:mm:ss");
            if (this.caction == "trend")
            {
                Node selectNode = this.atChineseDiagnose.SelectedNode;
                if (selectNode != null)
                {
                    Node parentNode = GetParentNode(selectNode);

                    int num = 0;
                    if (selectNode.Nodes.Count > 0)
                    {
                        int.TryParse((selectNode.Nodes[selectNode.Nodes.Count - 1].Tag as DataRow)["sort_sequence"].ToString(), out num);
                    }
                    t_simple_trend_diagnose tstd = new t_simple_trend_diagnose(parentNode.Name, diagnoseBm, this.lbChineseBmIcd.Text, this.lbChineseBmIcd.Text, num + 1, selectNode.Name);
                    if (tstd.Insert())
                    {
                        App.Msg("附属诊断添加成功！");
                    }
                }
            }
            else if (this.caction == "update")
            {
                Node selectNode = this.atChineseDiagnose.SelectedNode;
                if (selectNode != null)
                {
                    if (selectNode.Parent == null)
                    {
                        t_simple_diagnose tsd = new t_simple_diagnose(this.lbChineseBmIcd.Text, "", diagnoseBm, this.lbChineseBmIcd.Text, 0, 0, "Y", diagnoseZh, this.lbChineseZhIcd.Text);
                        if (tsd.Update(selectNode.Name))
                        {
                            App.Msg("诊断修改成功！");
                        }
                    }
                    else
                    {
                        t_simple_trend_diagnose tstd = new t_simple_trend_diagnose("", diagnoseBm, this.lbChineseBmIcd.Text, this.lbChineseBmIcd.Text, 0, "");
                        if (tstd.Update(selectNode.Name))
                        {
                            App.Msg("附属诊断修改成功！");
                        }
                    }
                }
            }
            else
            {
                int num = 0;
                if (this.atChineseDiagnose.Nodes.Count > 0)
                {
                    int.TryParse((this.atChineseDiagnose.Nodes[this.atChineseDiagnose.Nodes.Count - 1].Tag as DataRow)["diagnose_sort"].ToString(), out num);
                }
                t_simple_diagnose tsd = new t_simple_diagnose(this.lbChineseBmIcd.Text, timeStr, diagnoseBm, this.lbChineseBmIcd.Text, num + 1, document.Us.InpatientInfo.Id, "Y", diagnoseZh, this.lbChineseZhIcd.Text);
                if (tsd.Insert())
                {
                    App.Msg("诊断添加成功！");
                }
            }
            this.caction = string.Empty;
            this.atChineseDiagnose.Enabled = true;
            this.clearChineseDiagnose();
            RefreshDiagnose(atChineseDiagnose, "Y");
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Node selectNode = this.atChineseDiagnose.SelectedNode;
            if (selectNode != null)
            {
                this.caction = "trend";
                this.atChineseDiagnose.Enabled = false;
                clearChineseDiagnose();
                this.txtZh.Enabled = false;
            }
            else
            {
                App.Msg("请选中要添加附属诊断的节点！");
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Node selectNode = this.atChineseDiagnose.SelectedNode;
            if (selectNode != null)
            {
                this.caction = "update";
                this.atChineseDiagnose.Enabled = false;
                DataRow row = (DataRow)selectNode.Tag;
                this.txtBm.Text = selectNode.Text;
                this.lbChineseBmIcd.Text = row["diagnose_code"].ToString();
                if (selectNode.Parent == null)
                {
                    this.txtZh.Text = row["SYMPTOMS_NAME"].ToString();
                    this.lbChineseZhIcd.Text = row["SYMPTOMS_CODE"].ToString();
                }
                else
                {
                    this.txtZh.Text = "";
                    this.lbChineseZhIcd.Text = "";
                    this.txtZh.Enabled = false;
                }
            }
            else
            {
                App.Msg("请选中要修改的诊断节点！");
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            Node selectNode = this.atChineseDiagnose.SelectedNode;

            if (selectNode != null)
            {
                if (MessageBox.Show("确定要删除该诊断吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.No)
                    return;
                if (selectNode.Parent == null)
                {
                    t_simple_diagnose.Delete(selectNode.Name);
                    t_simple_trend_diagnose.Delete(selectNode.Name, 1);
                }
                else
                {
                    t_simple_trend_diagnose.Delete(selectNode.Name, 0);
                }
            }
            this.caction = string.Empty;
            this.atChineseDiagnose.Enabled = true;
            this.clearChineseDiagnose();
            RefreshDiagnose(atChineseDiagnose, "Y");
        }

        private void atChineseDiagnose_DoubleClick(object sender, EventArgs e)
        {
            atDiagnoseList_NodeDoubleClick(sender, null);
        }

        bool chineseChanged = false;
        private void atChineseDiagnose_AfterCheck(object sender, AdvTreeCellEventArgs e)
        {
            if (chineseChanged)
                return;
            Node selectNode = this.atChineseDiagnose.SelectedNode;
            if (selectNode != null)
            {
                ChildCheck(selectNode, selectNode.Checked);
            }
        }

        private void checkBoxItem1_Click(object sender, EventArgs e)
        {
            chineseChanged = true;
            if (this.atChineseDiagnose.Nodes.Count > 0)
            {
                foreach (Node node in this.atChineseDiagnose.Nodes)
                {
                    node.Checked = checkBoxItem1.Checked;
                    ChildCheck(node, node.Checked);
                }
            }
            chineseChanged = false;
        }

        private void buttonItem1_Click(object sender, EventArgs e)
        {
            ChangedNodeMoveUp(atChineseDiagnose);
        }

        private void buttonItem2_Click(object sender, EventArgs e)
        {
            ChangedNodeMoveDown(atChineseDiagnose);
        }
    }

    public class t_simple_diagnose
    {
        private string diagnose_code;

        public string Diagnose_code
        {
            get { return diagnose_code; }
            set { diagnose_code = value; }
        }
        private string create_time;

        public string Create_time
        {
            get { return create_time; }
            set { create_time = value; }
        }
        private string diagnose_name;

        public string Diagnose_name
        {
            get { return diagnose_name; }
            set { diagnose_name = value; }
        }
        private string diagnose_icd10;

        public string Diagnose_icd10
        {
            get { return diagnose_icd10; }
            set { diagnose_icd10 = value; }
        }
        private int diagnose_sort;

        public int Diagnose_sort
        {
            get { return diagnose_sort; }
            set { diagnose_sort = value; }
        }
        private int patient_id;

        public int Patient_id
        {
            get { return patient_id; }
            set { patient_id = value; }
        }

        private string is_chinese = "N";

        public string Is_chinese
        {
            get { return is_chinese; }
            set { is_chinese = value; }
        }

        private string symptoms_name;

        public string Symptoms_name
        {
            get { return symptoms_name; }
            set { symptoms_name = value; }
        }

        private string symptoms_code;

        public string Symptoms_code
        {
            get { return symptoms_code; }
            set { symptoms_code = value; }
        }

        public t_simple_diagnose(
            string code,
            string time,
            string name,
            string icd10,
            int sort,
            int pid)
        {
            this.diagnose_code = code;
            this.create_time = time;
            this.diagnose_name = name;
            this.diagnose_icd10 = icd10;
            this.diagnose_sort = sort;
            this.patient_id = pid;
        }

        public t_simple_diagnose(
            string code,
            string time,
            string name,
            string icd10,
            int sort,
            int pid,
            string is_chinese,
            string zhName,
            string zhIcd)
        {
            this.diagnose_code = code;
            this.create_time = time;
            this.diagnose_name = name;
            this.diagnose_icd10 = icd10;
            this.diagnose_sort = sort;
            this.patient_id = pid;
            this.symptoms_name = zhName;
            this.Symptoms_code = zhIcd;
            this.is_chinese = is_chinese;
        }


        public bool Insert()
        {
            string sql =
                string.Format("insert into t_simple_diagnose(diagnose_code,create_time,diagnose_name, diagnose_icd10,diagnose_sort,patient_id,is_chinese,symptoms_name,symptoms_code)values('{0}',to_TIMESTAMP('{1}','yyyy-MM-dd hh24:mi:ss'),'{2}','{3}','{4}','{5}','{6}','{7}','{8}')",
                diagnose_code,
                create_time,
                diagnose_name,
                diagnose_icd10,
                diagnose_sort,
                patient_id,
                is_chinese,
                symptoms_name,
                symptoms_code
                );
            if (App.ExecuteSQL(sql) > 0)
                return true;
            return false;
        }

        public static bool Delete(string id)
        {
            string sql = string.Format("delete t_simple_diagnose where id = '{0}'", id);
            if (App.ExecuteSQL(sql) > 0)
                return true;
            return false;
        }

        public bool Update(string id)
        {
            string sql
                = string.Format("update t_simple_diagnose " +
                  "set diagnose_code = '{0}'," +
                  "diagnose_name = '{1}'," +
                  "diagnose_icd10 = '{2}'," +
                  "symptoms_name = '{3}'," +
                  "symptoms_code = '{4}' " +
                  "where id = '{5}'",
                  diagnose_code,
                  diagnose_name,
                  diagnose_icd10,
                  symptoms_name,
                  symptoms_code,
                  id);
            if (App.ExecuteSQL(sql) > 0)
                return true;
            return false;
        }
    }

    public class t_simple_trend_diagnose
    {
        private string diagnoseitem_id;

        public string Diagnoseitem_id
        {
            get { return diagnoseitem_id; }
            set { diagnoseitem_id = value; }
        }
        private string trend_diagnose_name;

        public string Trend_diagnose_name
        {
            get { return trend_diagnose_name; }
            set { trend_diagnose_name = value; }
        }
        private string diagnose_icd10;

        public string Diagnose_icd10
        {
            get { return diagnose_icd10; }
            set { diagnose_icd10 = value; }
        }
        private string diagnose_code;

        public string Diagnose_code
        {
            get { return diagnose_code; }
            set { diagnose_code = value; }
        }
        private int sort_sequence;

        public int Sort_sequence
        {
            get { return sort_sequence; }
            set { sort_sequence = value; }
        }
        private string parent_id;

        public string Parent_id
        {
            get { return parent_id; }
            set { parent_id = value; }
        }

        public t_simple_trend_diagnose(
            string parentId,
            string name,
            string icd10,
            string code,
            int sort,
            string pid)
        {
            diagnoseitem_id = parentId;
            trend_diagnose_name = name;
            diagnose_icd10 = icd10;
            diagnose_code = code;
            sort_sequence = sort;
            parent_id = pid;
        }

        public bool Insert()
        {
            string sql = string.Format("insert into t_simple_trend_diagnose" +
                "(diagnoseitem_id, trend_diagnose_name, diagnose_icd10, diagnose_code, sort_sequence, parent_id)" +
                "values" +
                "('{0}', '{1}', '{2}', '{3}', {4}, {5})",
                diagnoseitem_id,
                trend_diagnose_name,
                diagnose_icd10,
                diagnose_code,
                sort_sequence,
                parent_id);
            if (App.ExecuteSQL(sql) > 0)
                return true;
            return false;
        }

        public static bool Delete(string id, int type)
        {
            string sql = string.Empty;
            if (type == 0)
                sql = string.Format("delete t_simple_trend_diagnose where id = {0}", id);
            else
                sql = string.Format("delete t_simple_trend_diagnose where parent_id ='{0}'", id);
            if (App.ExecuteSQL(sql) > 0)
                return true;
            return false;
        }

        public bool Update(string id)
        {
            string sql = string.Format(
                "update t_simple_trend_diagnose " +
                "set " +
                "trend_diagnose_name = '{0}'," +
                "diagnose_icd10 = '{1}'," +
                "diagnose_code = '{2}' " +
                "where id = '{3}'",
                trend_diagnose_name,
                diagnose_icd10,
                diagnose_code,
                id);
            if (App.ExecuteSQL(sql) > 0)
                return true;
            return false;
        }
    }
}
